#include "wheel.h"

using namespace tp1;

const float WheelComposite::ANGLE_GAP = 360.0f/QTIMES_OBJECT_DRAWN;

Wheel::Wheel(float radius,int qPieces,float radiusCylinders,int sidesCylinders)
	:Object3D(2*radiusCylinders)
{
	m_qDivisions = qPieces;
	m_rotationAngle = 0;

	// Angulo que forma cada pieza de rueda.
	float angle = 360.0f/(float)m_qDivisions;

	m_pattern = new Pattern(radius,angle,QOBLIQUECYLINDERS,radiusCylinders,sidesCylinders);

}


Wheel::~Wheel(void)
{
	delete m_pattern;
}

float Wheel::GetRadius()
{
	return m_pattern->GetRadius();
}

void Wheel::SetRadius(float radius)
{
	m_pattern->SetRadius(radius);
}

void Wheel::SetDivisions(int divisions)
{
	m_qDivisions = divisions;

	float angle = 360.0f/(float)m_qDivisions;
	m_pattern->SetAngle(angle);
}

void Wheel::Render()
{
	glPushMatrix();	
		for(int i = 0; i < m_qDivisions; i++)
			{
				m_pattern->Render();
				m_pattern->Rotate(m_pattern->GetAngle(),0,-1,0);
			}
	glPopMatrix();	
}

WheelComposite::WheelComposite(float radius,int qPieces,float radiusCylinders,int sidesCylinders,Object3D* object)
	:Object3D(object->Width()+4*radiusCylinders)
{
	m_wheel = new Wheel(radius,qPieces,radiusCylinders,sidesCylinders);
	m_cylinder = new Cylinder(radiusCylinders,Width(),sidesCylinders);

	m_object = object;
}

WheelComposite::~WheelComposite()
{
	delete m_wheel;
	delete m_cylinder;
}

void WheelComposite::Render()
{
	glPushMatrix();
		glTranslatef(0,(m_object->Width()+ m_wheel->Width())/2.0f,0);
		glRotatef(m_angleRotation,m_xrot,m_yrot,m_zrot);
		m_wheel->Render();		
		m_wheel->Translate(0,-(m_object->Width()+m_wheel->Width()),0);
		m_wheel->Render();
	glPopMatrix();
	
	glPushMatrix();
		for(int j = 0; j < QTIMES_OBJECT_DRAWN; j++)
		{	
			float angle = j*ANGLE_GAP + m_angleRotation;
			glPushMatrix();
				glTranslatef(m_wheel->GetRadius()*cosf(Mathematic::toRadians(angle)),0,m_wheel->GetRadius()*sinf(Mathematic::toRadians(angle)));
				glPushMatrix();
					m_cylinder->Translate(0,m_cylinder->GetHeight()/2.0f,0);
					m_cylinder->Rotate(90,1,0,0);
					m_cylinder->Render();
				glPopMatrix();				
				m_object->Render();
			glPopMatrix();
		}
	glPopMatrix();
}

void WheelComposite::Rotate(float angle,float x, float y, float z)
{
	m_angleRotation = angle;
	m_xrot = x;
	m_yrot = y;
	m_zrot = z;
}